import api from "../../utils/api_util";
import baseUtil from "../../utils/base_util";
import tips from "../../utils/tip";

const app = getApp();
Page({
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        HasBingAddress: true,
        isDelete: false,
        isEdit: false,
        disabled: false,
        code: '获取验证码',
        codeSrc:'',
        //收货
        area: ['北京市', '北京市', '东城区'],
        areaCode: [],
        phone: '',
        AddressList: [],
        updataId: '',
        //用户信息
        userInfo: [],
        msgCode: '',
        myAccount:'',
        unReadNum:'',
        teamNum:"",

    },
    onShow: function (options) {
        this.getUserData();
        this.getUserAddress();
        this.getAccount();
        this.getUnReadMsg();
        this.getMyTeam();
    },
    setDefaultAddress() {
        // let DefaultAddress = this.data.AddressList.find(item => item.checked == true);
        // if (typeof DefaultAddress == 'undefined') {
        //     wx.showToast({
        //         title: "您还没有选择默认的地址",
        //         icon: "none"
        //     })
        //     return
        // } else {
            this.setData({
                AddressListModal: null,
                isDelete: false,
            })
            // wx.showToast({
            //     title: "地址：" + DefaultAddress.area.join('') + DefaultAddress.address + "已经设置为默认地址",
            //     icon: "none"
            // })
        // }
    },

    // 关闭添加地址model,并初始化值
    closeAddressModal() {
        this.setData({
            addAddressModal: null,
            address: '',
            name: '',
            phone: '',
            // area: ["北京市", "北京市", "东城区"]
        })
    },
    // 新建地址-------跟添加地址一样
    newAddAddress() {
        this.setData({
            isEdit: false,
            addAddressModal: "addAddressModal"
        })
    },
    // 关闭地址列表model
    closeAddressListModal() {
        this.setData({
            AddressListModal: null,
            isDelete: false
        })
    },
    // Show添加地址model
    showAddressModal(e) {
        console.log(this.data.AddressList == 0);
        this.data.AddressList == 0 ? this.setData({
            isEdit: false,
            addAddressModal: "addAddressModal"
        }) : this.setData({
            isEdit: true,
            AddressListModal: "AddressListModal"
        })
    },
    // Show删除地址
    showDeleteAddress() {
        let AddressList = this.data.AddressList;
        this.setData({
            isDelete: !this.data.isDelete,
            AddressList
        })
    },
    // 下载二维码
    downLoadImage() {
        var that = this;
        wx.downloadFile({
            url: that.data.codeSrc,
            type: 'image',
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success: function () {
                        wx.showToast({
                            title: '保存成功'
                        })
                    },
                    fail: function (res) {
                        wx.showToast({
                            title: '保存失败',
                            icon: 'none'
                        })
                    }
                })
            },
            fail: function (err) {
                console.log(err)
            },
            complete: function (e) {
                console.log(e)
            }
        })
    },

    /**
     * 地址
     */
    //获取收货地址
    getUserAddress: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.addressList, {
            method: 'GET',
            data: {
                v: '1.0.0',
            },
            success: function (res) {

                res.data.rows.forEach(item => {
                    if (item.acquiescence == 'false') {
                        item.acquiescence = false;
                    } else {
                        item.acquiescence = true;
                    }
                })

                that.setData({
                    AddressList: res.data.rows
                })
            },
        })
    },
    // 确认修改原地址
    editAddress(e) {
        let that = this;

        api.wxRequest.apiRequest(that, api.urls.updataAddress, {
            method: 'POST',
            data: {
                v: '1.0.0',
                name: that.data.name,
                mobile: that.data.phone,
                address: that.data.address,
                provinceId: that.data.areaCode[0],
                cityId: that.data.areaCode[1],
                districtId: that.data.areaCode[2],
                id: that.data.updataId,
            },
            success: function (res) {
                that.setData({
                    AddressListModal: "AddressListModal",
                });

                that.getUserAddress();
                that.closeAddressModal();
            },
        })


    },
    // 选择默认地址
    radioChange(e) {
        let that = this;
        console.log(e.detail.value);
        api.wxRequest.apiRequest(that, api.urls.modifyAcquiescence, {
            method: 'POSt',
            data: {
                v: '1.0.0',
                id: e.detail.value,
            },
            success: function (res) {
                that.getUserAddress();
            },
        })
    },
    // 编辑地址，实际跟 添加地址用的同一个模态框
    editAddressModel(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;


        console.log('地址详情:', id);
        api.wxRequest.apiRequest(that, api.urls.detailsAddress, {
            method: 'GET',
            data: {
                v: '1.0.0',
                id: id,
            },
            success: function (res) {
                let AddressList = that.data.AddressList.find(item => item.id == id);
                // console.log(AddressList);
                that.data.areaCode[0] = res.data.provinceId;
                that.data.areaCode[1] = res.data.cityId;
                that.data.areaCode[2] = res.data.districtId;
                that.data.region = res.data.regionName;
                that.setData({
                    editaddressid: res.data.id,
                    name: res.data.name,
                    phone: res.data.mobile,
                    areaCode: that.data.areaCode,
                    area: res.data.regionName.split(','),
                    region: that.data.region,
                    address: AddressList.address,
                    addAddressModal: "addAddressModal",
                    isEdit: true,
                    updataId: id,
                })
            },
        })

    },
    // 删除地址按钮
    deleteAddress(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定删除收货地址吗？',
            success(res) {
                if (res.confirm) {
                    api.wxRequest.apiRequest(that, api.urls.deleteAddress, {
                        method: 'POST',
                        data: {
                            v: '1.0.0',
                            id: id,
                        },
                        success: function (res) {
                            that.getUserAddress();
                        },
                    })
                } else if (res.cancel) {
                }
            }
        })
    },
    // 三级地理位置连锁
    bindRegionChange: function (e) {
        console.log('地址：', e.detail.value);
        console.log('地址：', e);
        this.setData({
            area: e.detail.value,
            areaCode: e.detail.code
        })
    },
    // 收货人名
    watchName(e) {
        this.setData({
            name: e.detail.value
        })
    },
    // 收货手机号
    watchPhone(e) {
        this.setData({
            phone: e.detail.value
        })
    },
    // 地址
    watchAddress(e) {
        this.setData({
            address: e.detail.value
        })
    },
    // 添加地址
    AddAddress() {
        let that = this;
        if (this.data.name && this.data.phone && this.data.address) {
            let area = this.data.area;
            let address = this.data.address;
            let name = this.data.name;
            let phone = this.data.phone;

            api.wxRequest.apiRequest(that, api.urls.createAddress, {
                method: 'POST',
                data: {
                    v: '1.0.0',
                    name: name,
                    mobile: phone,
                    address: address,
                    provinceId: that.data.areaCode[0],
                    cityId: that.data.areaCode[1],
                    districtId: that.data.areaCode[2],
                },
                success: function (res) {
                    that.setData({
                        // AddressList,
                        addAddressModal: null,
                        AddressListModal: "AddressListModal",
                        // address: '',
                        // name: '',
                        // phone: '',
                        // region: ["北京市", "北京市", "东城区"]
                    });
                    that.getUserAddress();
                },
            })


            // let AddressList = [...this.data.AddressList, {
            //     id: 12,
            //     name,
            //     address,
            //     phone,
            //     area
            // }]

            // wx.showToast({
            //     title: "地址添加成功",
            //     icon: "none"
            // })
        } else {
            wx.showToast({
                title: '请填写完整',
                icon: "none"
            })
        }

    },
    /**
     * 用户信息
     */
    //获取用户信息
    getUserData: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.userInfo, {
            method: 'GET',
            data: {
                v: '1.0.0',
            },
            success: function (res) {
                that.setData({
                    userInfo: res.data,
                })

            },
            headerInfo: function (res) {
                baseUtil.setStorageSync('token', res.token);
            }
        })
    },
    //获取用户积分
    getAccount: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.myAccount, {
            method: 'GET',
            data: {
                v: '1.0.0',
            },
            success: function (res) {
                that.setData({
                    myAccount: res.data.usableIntegral,
                })
            },
        })
    },
    /**
     * 修改手机号
     */
    // 获取手机发送验证码
    getPhoneCodePost: function () {
        let that = this;
        let bingphone = that.data.bingphone;

        let isPass = /^[1][3,4,5,7,8][0-9]{9}$/.test(bingphone);
        if (!isPass) {
            wx.showToast({
                title: '手机号有误，请检查后确认',
                icon: 'none'
            })
            return
        }
        api.wxRequest.apiRequest(that, api.urls.sendVerifyCode, {
            method: 'POST',
            data: {
                v: '1.0.0',
                mobile: bingphone,
                type: 2,
            },
            success: function (res) {
                that.getPhoneCode();
            },
        })
    },
    getPhoneCode: function () {
        let that = this;
        let time = 60;
        wx.showToast({
            title: '短信验证码已发出，请稍等',
            icon: 'none'
        })
        that.setData({
            code: '60秒后重发',
            disabled: true
        })
        var Interval = setInterval(function () {
            time--;
            if (time > 0) {
                that.setData({
                    code: time + '秒后可重发'
                })
            } else {
                clearInterval(Interval);
                that.setData({
                    code: '获取验证码',
                    disabled: false
                })
            }
        }, 1000)
    },
// 绑定手机确认------绑定手机请求发送绑定手机号
    bindingPhone() {
        let that = this;
        let bingphone = that.data.bingphone;
        api.wxRequest.apiRequest(that, api.urls.modifyMobile, {
            method: 'POST',
            data: {
                v: '1.0.0',
                mobile: bingphone,
                originMobile: that.data.userInfo.mobile,
                code: that.data.msgCode,
            },
            success: function (res) {
                // that.getPhoneCode();
                tips.alert(res.data)
            },
        })
        this.setData({
            modalName: null
        })
    },
    // input监听手机号
    bingPhone(e) {
        this.setData({
            bingphone: e.detail.value
        })
    },
    //监听验证码
    msgCodeInput: function (e) {
        this.setData({
            msgCode: e.detail.value
        })
    },
    // Show绑定手机model
    showPhoneModal: function (e) {
        var modalName = e.currentTarget.dataset.modal;
        this.setData({
            modalName
        })
    },
    // Close绑定手机model
    closePhoneModal: function (e) {
        this.setData({
            modalName: null,
            bingphone: ''
        })
    },

    /**
     * 生产二维码
     */
    // Show二维码model
    showQrCode(e) {
        let modalName = e.currentTarget.dataset.modal;
        let that =this;
        // this.getWXACodeUnlimit();

        this.setData({
            modalName,
            codeSrc:api.urls.wxCode+'?v=1.0.0&inviteCode='+that.data.userInfo.inviteCode,
            // codeSrc:'http://192.168.38.200:9001/shuliang-app-api/wx/appletCode?v=1.0.0&inviteCode=4ffs'
        })
    },
    //生产二维码
    getWXACodeUnlimit: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.wxCode, {
            method: 'GET',
            data: {
              v:'1.0.0',
              page:'',
            },
            success: function (res) {

            },
        })
    },

    //未读消息数量
    getUnReadMsg: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.msgUnreadCount, {
            method: 'GET',
            data: {
                v:'1.0.0',
            },
            success: function (res) {

                that.setData({
                    unReadNum:res.data,
                })
            },
        })
    },
    //团队
    getMyTeam: function () {
        let that = this;
        api.wxRequest.apiRequest(that, api.urls.teamList, {
            method: 'GET',
            data: {
                v: '1.0.0',
                pageSize: '',
                pageNumber: '',
            },
            success: function (res) {

                that.setData({
                    teamNum: res.data.totalCount,
                })

            },
        })
    },
})